﻿
using Newtonsoft.Json;
using SuperSocket.SocketBase.Config;
using SuperWebSocket;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;


namespace WebNetSocket
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);



            /***启动socket***/
            SocketServer socket = new SocketServer(2333, "192.168.1.44", "开始");
            //启动线程  
            Thread thread = new Thread(new ThreadStart(socket.beginListen));
            thread.Start();

            /**启动webSocketServer**/
            // WebSocketServer websocket = new WebSocketServer(2333, "192.168.1.44", "开始");
            //启动线程  
            Thread webthread = new Thread(new ThreadStart(new WebSocketServerCli().Start));
            webthread.Start();


            /**监听一个端口**/
            Thread webthread3721 = new Thread(new ThreadStart(Listen3721));
            webthread3721.Start();

            /***supperWebSocket***/
            Thread webthread400011 = new Thread(new ThreadStart(SuperWebSocketServer.Init));
            webthread400011.Start();

            
        }

        public void Listen3721()
        {
            try
            {
                IPAddress ip = IPAddress.Parse("192.168.1.44");
                //在3721端口新建一个TcpListener对象
                TcpListener listener = new TcpListener(ip, 3721);
                listener.Start();
                Console.WriteLine("started listening..");
                //开始监听
                while (true)
                {
                    Socket s = listener.AcceptSocket();
                    
                    string remote = s.RemoteEndPoint.ToString();
                    //允许js跨越访问
                    var bytes = System.Text.Encoding.UTF8.GetBytes("HTTP/1.1 200 OK\r\nAccess-Control-Allow-Origin: * \r\n\r\nOK");
                    s.Send(bytes);
                    //s.Shutdown(SocketShutdown.Send);
                }
            }
            catch (System.Security.SecurityException)
            {
                Console.WriteLine("firewall says no no to application – application cries..");
            }
            catch (Exception)
            {
                Console.WriteLine("stoped listening..");
            }
        }

    }
     
    /// <summary>
    /// Socket server
    /// </summary>
    public class SocketServer
    {

        int port;  //端口
        string host;//ip地址
        string txt;
        /// <summary>
        /// 构造涵数
        /// </summary>
        /// <param name="ports">端口号</param>
        public SocketServer(int ports, string host, string txt)
        {
            this.port = ports;
            this.host = host;
            this.txt = txt;
        }
        //开始监听
        public void beginListen()
        {
            try
            {
                IPAddress ip = IPAddress.Parse(host);//把ip地址字符串转换为IPAddress类型的实例
                IPEndPoint ipe = new IPEndPoint(ip, port);//用指定的端口和ip初始化IPEndPoint类的新实例
                                                          ///创建socket并开始监听
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建一个socket对像，如果用udp协议，则要用SocketType.Dgram类型的套接字
                s.Bind(ipe);//绑定EndPoint对像（端口和ip地址）
                s.Listen(0);//开始监听
                txt += "等待客户端连接";
                // Console.WriteLine("等待客户端连接");
                //定义循环，以便可以简历多次连接
                while (true)
                {
                    Socket temp = s.Accept();//为新建连接创建新的socket               
                    while (true)
                    {
                        string recvStr = "";
                        byte[] recvBytes = new byte[1024];
                        int bytes;
                        bytes = temp.Receive(recvBytes, recvBytes.Length, 0);//从客户端接受信息
                        recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);
                        txt += "\r\n" + recvStr + "\r\n";
                        if (recvStr.IndexOf("<EOF>") > -1)
                        {
                            break;
                        }

                        byte[] bs = Encoding.ASCII.GetBytes(recvStr);
                        temp.Send(bs, bs.Length, 0);//返回信息给客户端

                    }
                    //给client端返回信息
                    // Console.WriteLine("server get message:{0}", recvStr);//把客户端传来的信息显示出来
                }
            }
            catch (Exception ex)
            {
                string str = ex.ToString();
                txt += "\r\n" + str + "\r\n";
            }
        }
    }

    /// <summary>
    /// 监听
    /// </summary>
    public class WebSocketServerCli
    {
        public void Start()
        {
            int e = 2;
            if(HttpContext.Current!=null&&HttpContext.Current.IsWebSocketRequest)
            {
                int a = 1;
            }
        }
    }
    

    /// <summary>
    /// supperWebSocket
    /// </summary>
    public  class SuperWebSocketServer
    {
        public static WebSocketServer server;
        private static List<SessionInfo> listSession = new List<SessionInfo>();
        /// <summary>
        /// 活动会话映射表(k:userId,v:socketSessionId)
        /// </summary>
        public static Dictionary<string, string> SessionMap = new Dictionary<string, string>();


        public static void Init()
        {
            Start();
        }

        /// <summary>
        /// 服务启动
        /// </summary>
        /// <param name="port">端口号</param>
        /// <returns></returns>
        public static WebSocketServer Start()
        {
            string port ="56586";
            var ip = "0.0.0.0";
            server = new WebSocketServer();
            var config = new ServerConfig();
            config.Port = int.Parse(port);
            config.Ip = ip;
            
            config.MaxConnectionNumber = 100000;//最大并发数量
            
            if (!server.Setup(config))
            {
                throw new Exception("WebSocket服务启动Error");
            }
           
            //新的会话连接
            server.NewSessionConnected += SessionConnected;
            //会话关闭
            server.SessionClosed += SessionClosed;
            //新的消息接收
            server.NewMessageReceived += MessageReceived;
       
            if (!server.Start())
            {
                //处理监听失败消息
                throw new Exception("消息监听失败");
            }
            return server;
        }


        /// <summary>
        /// 会话关闭
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private static void SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            var str = string.Format("会话关闭，关闭原因：{0}  来自：{1}  时间:{2:HH:MM:ss}", value, session.RemoteEndPoint, DateTime.Now);
       
            //Debug.WriteLine("会话关闭，关闭原因：{0}  来自：{1}  时间:{2:HH:MM:ss}", value, session.RemoteEndPoint, DateTime.Now);
            //SendMsgToRemotePoint(SessionId, SessionId + "已断开");
            var sessionRemove = listSession.FirstOrDefault(s => s.SessionId == session.SessionID);
            listSession.Remove(sessionRemove);
            //从map中移除关闭的客户端信息
          
          
        }

        /// <summary>
        /// 会话连接
        /// </summary>
        /// <param name="session"></param>
        private static void SessionConnected(WebSocketSession session)
        {
           
            try
            {
                var endPoint = session.RemoteEndPoint.ToString();


                //Debug.WriteLine("新的会话连接  来自：{0} SessionID:{1}  时间:{2:HH:MM:ss}", session.RemoteEndPoint, session.SessionID, DateTime.Now);
                listSession.Add(new SessionInfo { SessionId = session.SessionID, EndPoint = endPoint });
                
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        /// <summary>
        /// 消息接收
        /// </summary>
        /// <param name="session"></param>
        /// <param name="value"></param>
        private static void MessageReceived(WebSocketSession session, string value)
        {
            try
            {
                //反序列化消息内容
                var message =value;
               
                SendMsg(session.SessionID,message);
            }
            catch (Exception ex)
            {
               
            }
            //LogHelper.WriteLog(string.Format("{0}||{1}", message.Flag, message.Message));
            //foreach (var item in listSession)
            //{

            //    ///发送消息
            //    SendMsg(item.SessionId, string.Format("{0}发来消息：{1}", message.Name, message.Message));
            //}
        }

        // <summary>
        /// 发送消息
        /// </summary>
        /// <param name="sessionId"></param>
        /// <param name="msg"></param>
        public static void SendMsg(string sessionId, string msg)
        {
            var appSession = server.GetAppSessionByID(sessionId);
            if (appSession != null)
            {
                appSession.Send(msg);
            }

             
        }


        public class MessageInfo
        {
            public string Name { get; set; }
            public string Message { get; set; }
            public string ToName { get; set; }
            public string Flag { get; set; }
        }

        public class SessionInfo
        {
            public string SessionId { get; set; }
            public string EndPoint { get; set; }
            //public string Name { get; set; }
        }
    }

}
